package com.bluexmicro.ota.ui

import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.text.Html
import android.text.method.LinkMovementMethod
import android.util.Log
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.bluexmicro.module_componment.file.ChooseFileActivity
import com.bluexmicro.module_componment.scan.ChooseDeviceActivity
import com.bluexmicro.ota.databinding.ActivityExampleBinding
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean

class ExampleActivity : AppCompatActivity() {

    private lateinit var binding: ActivityExampleBinding
    private val viewModel: ExampleViewModel by viewModels()
    private val fileAdapter = SelectedFileAdapter { context, fileResult ->
        viewModel.removeFile(context, fileResult)
    }
    private val undoneColors = ColorStateList.valueOf(Color.parseColor("#D5D5D5"))
    private val doneColors = ColorStateList.valueOf(Color.parseColor("#50B450"))

    private var chooseFileLauncher: ActivityResultLauncher<Int>? = null
    private var chooseDeviceLauncher: ActivityResultLauncher<Int>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityExampleBinding.inflate(layoutInflater)
        setContentView(binding.root)

        //加载sp
        viewModel.loadTasks(this)
        viewModel.loadFastMode(this)

        chooseFileLauncher =
            registerForActivityResult(ChooseFileActivity.getActivityResultContract()) {
                if (it != null) viewModel.appendFile(this@ExampleActivity, it)
            }

        chooseDeviceLauncher =
            registerForActivityResult(ChooseDeviceActivity.getActivityResultContract()) {
                if (it != null) viewModel.setTarget(it)
            }

        binding.step1Header.apply {
            stepNumTx.text = "1"
            stepTitleTx.text = "选择Firmware/Material"
        }
        binding.step2Header.apply {
            stepTitleTx.text = "选择目标设备"
            stepNumTx.text = "2"
        }
        binding.step3Header.apply {
            stepTitleTx.text = "开始升级"
            stepNumTx.text = "3"
        }
        binding.otaTasksListView.apply {
            layoutManager = LinearLayoutManager(context)
            addItemDecoration(SpaceItemDecoration(bottomDp = 8))
            adapter = fileAdapter
        }
        binding.apply {
            chooseFileBtn.setOnClickListener {
                chooseFileLauncher?.launch(0)
            }
            chooseTargetBtn.setOnClickListener {
                chooseDeviceLauncher?.launch(0)
            }
            startBtn.setOnClickListener {
                viewModel.startOta(it.context)
            }

            fastModeSwitch.setOnClickListener {
                viewModel.toggleFastMode(it.context)
            }
        }
        setTips()

        lifecycleScope.launch {
            viewModel.modelState.collect {
                updateUI(it)
            }
        }
        lifecycleScope.launch {
            viewModel.otaStateFlow.collect {
                fileAdapter.updateState(it)
            }
        }
    }

    private fun updateUI(model: ExampleModel) {
        binding.root.keepScreenOn = model.updating
        fileAdapter.setUpdating(model.updating, true)
        fileAdapter.submitList(model.selectedFiles)

        binding.apply {
            fastModeSwitch.isChecked = model.fastMode
            fastModeSwitch.isEnabled = !model.updating

            chooseFileBtn.isEnabled = if (model.updating) {
                false
            } else {
                model.fastMode || model.selectedFiles.isEmpty()
            }

            chooseTargetBtn.isEnabled = !model.updating
            chooseTargetBtn.text = model.selectedDevice?.address ?: "选择"

            startBtn.text = if (model.fastMode) "开始（FastMode）" else "开始"
            startBtn.isEnabled = if (model.updating) {
                false
            } else {
                model.selectedFiles.isNotEmpty() && model.selectedDevice != null
            }
        }
        binding.step1Header.apply {
            val done = model.selectedFiles.isNotEmpty()
            stepNumTx.visibility = getShowFlag(!done)
            stepResultIcon.visibility = getShowFlag(done)
            stepBgView.backgroundTintList = if (done) doneColors else undoneColors
        }
        binding.step2Header.apply {
            val done = model.selectedDevice != null
            stepNumTx.visibility = getShowFlag(!done)
            stepResultIcon.visibility = getShowFlag(done)
            stepBgView.backgroundTintList = if (done) doneColors else undoneColors
        }
        binding.step3Header.apply {

        }
    }

    private fun getShowFlag(show: Boolean): Int {
        return if (show) View.VISIBLE else View.GONE
    }

    private fun setTips() {
        val version = try {
            val info = packageManager.getPackageInfo(packageName, 0)
            info.versionName
        } catch (ignore: Exception) {
            "Unknown Version"
        }
        val downloadNewVersion = "<a href='https://www.pgyer.com/C3EW'>(获取新版本)</a>"

//        1. FastMode 支持一次升级多个文件。
//        \n2. FastMode 每包传输更多的数据，与MTU有关。
//        \n3. 普通模式和FastMode是互斥的，升级前请确认设备支持哪一种模式。
        val sb = StringBuffer()
        sb.append("1. FastMode 支持一次升级多个文件。<br />")
        sb.append("2. FastMode 每包传输更多的数据，与MTU有关。<br />")
        sb.append("3. 普通模式和FastMode是互斥的，升级前请确认设备支持哪一种模式。<br />")
        sb.append("4. 当前版本: <b><font color=\"#000000\">").append(version).append("</font></b>; ")
            .append(downloadNewVersion)
        binding.tipsContentTx.text = Html.fromHtml(sb.toString(), Html.FROM_HTML_MODE_LEGACY)
        binding.tipsContentTx.movementMethod = LinkMovementMethod.getInstance()
    }
}